import 'dart:async';
import 'dart:ui' as ui;

import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:eplorex/models/metric_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../dao/location_dao.dart';
import '../../providers/map_provider.dart';
import '../../widgets/GridItemWidget.dart';
import 'map_config.dart';

class MapShowPage extends StatefulWidget {
  @override
  State<MapShowPage> createState() => _MapShowPageState();
}

class _MapShowPageState extends State<MapShowPage> {
  AMapController? _mapController;
  late Map<String, Marker> markerMap;
  late final List<LatLng> _points = [];
  late double nowLatitude;
  late double nowLongitude;
  late AMapApiKey aMapApiKey;
  late MapType _mapType;
  late bool _isRunning = false;
  late AMapPrivacyStatement aMapPrivacyStatement;
  Future<List<MetricItem>>? _runSummary;
  Color _splashColor = Colors.blue.withOpacity(0.5);
  int _mapStyleIndex = 0;
  Timer? _timer;
  late num _pathId = 0;

  @override
  void initState() {
    AMapProvider.instance.startLocation((Map<String, Object> result) {
      nowLatitude = double.parse(result['latitude'] as String);
      nowLongitude = double.parse(result['longitude'] as String);
      _points.add(LatLng(nowLatitude, nowLongitude));
      if (_pathId > 0) {
        LocationDao.reportLocation(result, _pathId, lastLoc: !_isRunning);
      }
      if (_mapController != null) {
        CameraUpdate cameraUpdate = CameraUpdate.newCameraPosition(
          CameraPosition(
            target: LatLng(nowLatitude, nowLongitude),
            zoom: 15,
            tilt: 0,
            bearing: 0,
          ),
        );
        _mapController?.moveCamera(cameraUpdate);
      }
    });

    markerMap = {};
    aMapApiKey =  AMapApiKey(
      iosKey: MapConfig.iosKey,
      androidKey: MapConfig.androidKey,
    );
    aMapPrivacyStatement = const AMapPrivacyStatement(
      hasContains: true,
      hasShow: true,
      hasAgree: true,
    );
    _mapType = MapType.normal;
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer?.cancel();
    }
    _mapController?.disponse();
  }

  _changeMapStyle() {
    setState(() {
      _mapStyleIndex = (_mapStyleIndex + 1) % MapType.values.length;
      _mapType = MapType.values.elementAt(_mapStyleIndex);
    });
  }

  _startTracing() {
    LocationDao.createPath("开始").then((value) {
      _points.clear();
      _pathId = value! as num;
      AMapProvider.instance.startPluginLocation();
      _timer = Timer.periodic(Duration(seconds: 10), (timer) {
        AMapProvider.instance.startPluginLocation();
      });
      setState(() {
        _points.add(LatLng(nowLatitude, nowLongitude));
      });
    });
  }

  _stopTracing() {
    print("_stopTracing called");
    // 上报最后一个点位
    _timer?.cancel();
    AMapProvider.instance.startPluginLocation();
    Future.delayed(Duration(milliseconds: 500), () {
      AMapProvider.instance.stopLocation();
    });
    _runSummary = LocationDao.querySummary(_pathId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: Stack(
          children: [
            AMapWidget(
              apiKey: aMapApiKey,
              mapType: _mapType,
              privacyStatement: aMapPrivacyStatement,
              onMapCreated: onMapCreated,
              compassEnabled: false,
              markers: Set.of(markerMap.values),
              polylines: {
                Polyline(points: _points, color: Colors.blue, width: 8)
              },
            ),
            DraggableScrollableSheet(
                initialChildSize: 0.3,
                maxChildSize: 0.6,
                minChildSize: 0.2,
                expand: true,
                snap: false,
                builder:
                    (BuildContext context, ScrollController scrollController) {
                  return Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius:
                            BorderRadius.vertical(top: Radius.circular(16))),
                    child: SingleChildScrollView(
                      controller: scrollController,
                      child: Column(
                        children: [
                          InkWell(
                            borderRadius: BorderRadius.circular(50),
                            splashColor: _splashColor,
                            onLongPress: () {
                              if (_isRunning) {
                                setState(() {
                                  _isRunning = !_isRunning;
                                });
                              }
                              _stopTracing();
                            },
                            onTap: () {
                              _startTracing();
                              setState(() {
                                if (!_isRunning) {
                                  _isRunning = !_isRunning;
                                }
                                _splashColor = Colors.blue.withOpacity(0.1);
                              });
                              Future.delayed(Duration(milliseconds: 300), () {
                                setState(() {
                                  _splashColor = Colors.blue.withOpacity(0.5);
                                });
                              });
                            },
                            child: Container(
                              margin: EdgeInsets.only(top: 20),
                              width: 120,
                              height: 120,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: _isRunning ? Colors.red : Colors.blue,
                                  shape: BoxShape.circle),
                              child: Text(
                                _isRunning ? "结束" : "开始",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20,
                                    color: Colors.white),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            padding: EdgeInsets.zero,
                            alignment: Alignment.topLeft,
                            margin: EdgeInsets.symmetric(
                                horizontal: 20, vertical: 0),
                            height: 210,
                            child: Column(
                              // crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text("运动数据", style: TextStyle(fontSize: 18)),
                                FutureBuilder(
                                    future: _runSummary,
                                    builder: (BuildContext context,
                                        AsyncSnapshot<List<MetricItem>>
                                            snapshot) {
                                      return builderRunSummary(
                                          context, snapshot);
                                    })
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }),
            Positioned(
              right: 10,
              top: MediaQuery.sizeOf(context).height / 3,
              child: IconButton(
                padding: EdgeInsets.zero,
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.black12)),
                onPressed: _changeMapStyle,
                icon: Icon(Icons.layers_sharp),
              ),
            ),
            // Positioned(
            //   left: 10,
            //   top:40,
            //   child: BackButton(),
            // ),
          ],
        ),
      ),
    );
  }

  void onMapCreated(AMapController controller) {
    CameraUpdate cameraUpdate = CameraUpdate.newCameraPosition(
      CameraPosition(
        target: LatLng(nowLatitude, nowLongitude),
        zoom: 15,
        tilt: 0,
        bearing: 0,
      ),
    );
    controller.moveCamera(cameraUpdate);
    setState(() {
      _mapController = controller;
    });
    getMarker(
      nowLatitude,
      nowLongitude,
      // image: "images/my_position.png",
      title: "我",
    );
  }

  Future<String?> getApprovalNumber() async {
    // 普通地图审图号
    String? mapContentApprovalNumber =
        await _mapController?.getMapContentApprovalNumber();
    // // 卫星地图审图号
    // String? satelliteImageApprovalNumber =
    //     await _mapController.getSatelliteImageApprovalNumber();
    return mapContentApprovalNumber;
  }

  Future<BitmapDescriptor> getBitmapDescriptorFromAssetBytes(
    String path,
    double width,
    double height,
  ) async {
    var imageFile = await rootBundle.load(path);
    var pictureRecorder = ui.PictureRecorder();
    var canvas = Canvas(pictureRecorder);
    var imageUint8List = imageFile.buffer.asUint8List();
    var codec = await ui.instantiateImageCodec(imageUint8List);
    var imageFI = await codec.getNextFrame();
    paintImage(
      canvas: canvas,
      rect: Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
      image: imageFI.image,
      filterQuality: FilterQuality.medium,
    );
    var image = await pictureRecorder
        .endRecording()
        .toImage(width.toInt(), height.toInt());
    var data = await image.toByteData(format: ui.ImageByteFormat.png);
    return BitmapDescriptor.fromBytes(data!.buffer.asUint8List());
  }

  Future<void> getMarker(
    double latitude,
    double longitude, {
    String? image,
    String? title,
    String? snippet,
  }) async {
    LatLng position = LatLng(latitude, longitude);
    Marker marker = Marker(
      onTap: (s) {
        print(s);
      },
      infoWindow: InfoWindow(
        title: title,
        snippet: snippet,
      ),
      position: position,
      icon: image != null
          ? await getBitmapDescriptorFromAssetBytes(image, 100, 100)
          : BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
    );
    markerMap[marker.id] = marker;
    // setState(() {});
  }

  Widget builderRunSummary(
      BuildContext context, AsyncSnapshot<List<MetricItem>> snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting ||
        snapshot.data == null) {
      return SizedBox(
        height: 1,
      );
    }
    List<MetricItem> metricItems = snapshot.data!;
    return GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisSpacing: 14,
          mainAxisExtent: 70,
          crossAxisCount: 3,
        ),
        itemCount: metricItems.length,
        itemBuilder: (context, index) {
          return GridItemWidget(
            title: metricItems[index].title ?? "未知",
            data: metricItems[index].value ?? "",
            unit: metricItems[index].unit ?? "",
          );
        });
  }
}
